package blue.base.internal.core.http;


import blue.base.core.http.Response;
import blue.base.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jin Zheng
 * @date 2020-07-08
 */
public class AbstractResponse<T> implements Response<T> {
	private static Logger logger = LoggerFactory.getLogger(AbstractResponse.class);

	private int code;
	private Map<String, String> headers;
	private Map<String, List<String>> map;
	private T body;

	public AbstractResponse(HttpResponse<T> response) {
		this.code = response.statusCode();
		this.body = response.body();
		this.map = response.headers().map();
		this.initHeaders();
		logger.info("Response, code: {}", code);
	}

	private void initHeaders() {
		if (map == null || map.isEmpty()) {
			return;
		}

		headers = new HashMap<>();
		for (Map.Entry<String, List<String>> entry : map.entrySet()) {
			headers.put(entry.getKey(), StringUtil.join(entry.getValue(), CONCAT));
		}
	}

	@Override
	public int getCode() {
		return code;
	}

	@Override
	public Map<String, String> getHeaders() {
		return headers;
	}

	@Override
	public Map<String, List<String>> getMap() {
		return map;
	}

	@Override
	public T getBody() {
		return body;
	}
}
